// pages/search/index.js
var util = require('../../utils/util.js');
Page({
  data: {
    expertList: [],
    routeList: [],
  },
  properties: {},
  initPartner(arr, size) {
    // 遍历获取
    var oddArr = []; // 奇数数组
    var evenArr = []; // 偶数数组
    for (let i = 0; i < arr.length; i++) {
      // 偶数下标

      if (i % 2 == 0) {
        oddArr.push(arr[i])
      } else {
        // 奇数下标
        evenArr.push(arr[i])
      }
    }
    let _arr = [oddArr, evenArr]

    return _arr
  },
  screenShow() {
    let that = this;
    this.setData({
      screenShow: true
    })
    that.selectComponent('#monthSlider').show();
    that.selectComponent('#daySlider').show();
  },
  screenHide() {
    this.setData({
      screenShow: false
    })
  },
  abroadShow() {
    this.setData({
      abroadShow: true
    })
  },
  abroadHide() {
    this.setData({
      abroadShow: false
    })
  },
  domesticShow() {
    this.setData({
      domesticShow: true
    })
  },
  domesticHide() {
    this.setData({
      domesticShow: false
    })
  },

  //确认事件
  abroadConfirm(e) {
    this.abroadHide();
    console.log(e.detail.values);
    let values = e.detail.values.map(item => item && item.name);
    values = values.filter(item => item && item.length > 0);
    this.setData({
      abroadAddr: values[values.length - 1],
      inlandAddr: '省-市'
    });
    this.data.abroadAddr = values.join('-');
  },
  domesticConfirm(e) {
    this.domesticHide();
    console.log(e.detail.values);
    let values = e.detail.values.map(item => item && item.name);
    values = values.filter(item => item && item.length > 0);
    this.setData({
      inlandAddr: values[values.length - 1],
      abroadAddr: '国家-地区'
    });
    this.data.inlandAddr = values.join('-');
  },

  addChange(event) {
    console.log(event)
    this.setData({
      result: event.detail
    });
  },
  leftMonthChange(e) {
    this.setData({
      leftMonth: e.detail.lowValue + '月'
    })
    this.data.leftMonth = e.detail.lowValue;
  },
  rightMonthChange(e) {
    this.setData({
      rightMonth: e.detail.heighValue + '月'
    })
    this.data.rightMonth = e.detail.heighValue;
  },
  leftDayChange(e) {
    this.setData({
      leftDay: e.detail.lowValue + '天'
    })
    this.data.leftDay = e.detail.lowValue;
  },
  rightDayChange(e) {
    this.setData({
      rightDay: e.detail.heighValue + '天'
    })
    this.data.rightDay = e.detail.heighValue;
  },
  choseType(e) {
    this.setData({
      screenType: e.currentTarget.dataset.index,
      screenName: e.currentTarget.dataset.name
    })
  },

  //重置搜索条件
  resetSearch() {
    this.setData({
      result: '出发',
      abroadAddr: '国家-地区',
      inlandAddr: '省-市',
      screenType: 0,
    });
  },

  //发出搜索请求
  goSearch() {
    console.log(this.data.leftMonth)
    let that = this;
    let is_abroad = 1;
    let reqData = {
      offset: this.data.offset,
      limit: this.data.limit,
      is_abroad: 1, //	1国内 2国外
      start_month: this.data.leftMonth,
      end_month: this.data.rightMonth,
      start_day: this.data.leftDay,
      end_day: this.data.rightDay,
      classify_id: this.data.screenTypeList[this.data.screenType].classify_id
    };
    console.log(this.data.result);
    if (this.data.abroadAddr != '国家-地区') {
      reqData.is_abroad = 2;
    }
    let addr = [];
    if (reqData.is_abroad == 1 && this.data.inlandAddr != '省-市') { //国内
      addr = ['中国'].concat(this.data.inlandAddr.split("-"));
    } else if (reqData.is_abroad == 2 && this.data.abroadAddr != '国家-地区') { //国外
      addr = this.data.abroadAddr.split("-");
    }
    if (this.data.result.indexOf('出发') >= 0) {
      reqData.start_province = addr.length > 1 ? addr[1] : '';
      reqData.start_city = addr.length > 2 ? addr[2] : '';
    }
    if (this.data.result.indexOf('目的地') >= 0) {
      reqData.end_country = addr.length > 0 ? addr[0] : '';
      reqData.end_province = addr.length > 1 ? addr[1] : '';
      reqData.end_city = addr.length > 2 ? addr[2] : '';
    }
    console.log("--------request data");
    console.log(reqData);

    util.http({
      url: '/api/miniwechat/index/search',
      method: 'POST',
      data: reqData
    }).then(res => {
      console.log("-------------👇");
      console.log(res);
      if (!res.line.rows) {
        wx.showToast({
          title: '查无数据',
          icon: 'none',
          duration: 2000
        })
        return;
      }
      res.line.rows.forEach((item, index) => {
        if (!item.line_time_list || item.line_time_list.length == 0) {
          return;
        }
        let beginTime = item.line_time_list.begin_time
        let endTime = item.line_time_list.end_time
        console.log(beginTime)
        console.log(endTime)
        let totalTime = (new Date(endTime).getTime() - new Date(beginTime).getTime()) / (1 * 24 * 60 * 60 * 1000)
        let surplusNum = item.line_time_list.quota - item.line_time_list.number
        item.line_time_list.totalTime = totalTime
        item.line_time_list.begin_time = timeReset(beginTime)
        item.line_time_list.end_time = timeReset(endTime)
        item.line_time_list.surplusNum = surplusNum
        switch (item.line_time_list.status) {
          case 0:
            item.line_time_list.state = '已取消'
            break;
          case 1:
            item.line_time_list.state = '报名中'
            break;
          case 2:
            item.line_time_list.state = '报名结束'
            break;
          case 3:
            item.line_time_list.state = '已完成'
            break;
        }
      })
      //渲染搜索结果↓↓↓↓↓↓↓↓↓↓↓↓↓
      that.setData({
        routeList: this.initPartner(res.line.rows, 2),
        expertList: res.guide.rows,
        screenShow: false,
        keyShow: true
      })
    }).catch(err => {
      console.log(err);
      wx.showToast({
        title: String(err),
        icon: 'none',
        duration: 2000
      })
    })
  },

  getSearch() {
    let that = this;
    util.http({
      url: '/api/miniwechat/index/search'
    }).then(res => {
      console.log("-------------👇");
      console.log(res);
      //渲染搜索结果↓↓↓↓↓↓↓↓↓↓↓↓↓
      res.line.rows.forEach((item, index) => {
        if (!item.line_time_list || item.line_time_list.length == 0) {
          return;
        }
        let beginTime = item.line_time_list.begin_time
        let endTime = item.line_time_list.end_time
        let totalTime = (new Date(endTime).getTime() - new Date(beginTime).getTime()) / (1 * 24 * 60 * 60 * 1000)
        let surplusNum = item.line_time_list.quota - item.line_time_list.number
        item.line_time_list.totalTime = totalTime
        item.line_time_list.begin_time = timeReset(beginTime)
        item.line_time_list.end_time = timeReset(endTime)
        item.line_time_list.surplusNum = surplusNum
        switch (item.line_time_list.status) {
          case 0:
            item.line_time_list.state = '已取消'
            break;
          case 1:
            item.line_time_list.state = '报名中'
            break;
          case 2:
            item.line_time_list.state = '报名结束'
            break;
          case 3:
            item.line_time_list.state = '已完成'
            break;
        }
      })
      that.setData({
        routeList: this.initPartner(res.line.rows, 2),
        expertList: res.guide.rows
      })
      console.log(this.data.routeList)
    }).catch(err => {
      console.log(err);
      wx.showToast({
        title: String(err),
        icon: 'none',
        duration: 2000
      })
    })
  },

  goRouteDetail(e) {
    wx.navigateTo({
      url: '/pages/routeDetail/index?id=' + e.currentTarget.dataset.id,
    })
  },
  goExpertDetail(e) {
    wx.navigateTo({
      url: '/pages/expertDetail/index?id=' + e.currentTarget.dataset.id
    })
  },

  goExpertMore() {
    wx.navigateTo({
      url: '/pages/expertList/index'
    })
  },
  goRouteListMore() {
    wx.navigateTo({
      url: '/pages/routeList/index'
    })
  },

  //获取线路主题分类
  getLineClassify() {
    let that = this;
    util.http({
      url: '/api/miniwechat/index/line_classify',
    }).then(res => {
      console.log("--------------getLineClassify");
      console.log(res);
      that.setData({
        screenTypeList: res
      });
    }).catch(err => {
      console.log(err);
      wx.showToast({
        title: String(err),
        icon: 'none',
        duration: 2000
      })
    })
  },

  //格式化国内地址
  formatAddr(addrData) {
    let inland = addrData[0];
    var inlandProv = {};
    var inlandCity = {};
    var inlandCounty = {};
    var code = 10;
    for (let i = 0, j = inland.s.length; i < j; ++i) {
      code++;
      let prov = inland.s[i];
      let provCode = code * 10000;
      inlandProv[provCode] = prov.n;
      let provCity = prov.s;
      if (!provCity[0].s) { //直辖市下没有市
        provCity = prov;
        let cityCode = provCode + 100;
        inlandCity[cityCode] = provCity.n;
        let cityCounty = provCity.s;
        for (let p = 0, q = cityCounty.length; p < q; ++p) {
          let countyCode = cityCode + p + 1;
          let county = cityCounty[p];
          inlandCounty[countyCode] = county.n;
        }
        continue;
      }
      for (let l = 0, m = provCity.length; l < m; ++l) {
        let cityCode = provCode + (l + 1) * 100;
        let city = provCity[l];
        inlandCity[cityCode] = city.n;
        let cityCounty = city.s;
        if (!cityCounty) { //一些市下面，没有县
          // console.log(city);
          continue;
        }
        for (let p = 0, q = cityCounty.length; p < q; ++p) {
          let countyCode = cityCode + p + 1;
          let county = cityCounty[p];
          inlandCounty[countyCode] = county.n;
        }
      }
    }

    this.setData({
      domesticList: {
        province_list: inlandProv,
        city_list: inlandCity,
        county_list: inlandCounty
      }
    });
  },

  //格式化国外地址
  formatAbroadAddr(addrData) {
    let abroad = addrData.slice(1);
    var abroadProv = {};
    var abroadCity = {};
    var abroadCounty = {};
    var code = 10;
    for (let i = 0, j = abroad.length; i < j; ++i) {
      code++;
      let prov = abroad[i];
      let provCode = code * 10000;
      abroadProv[provCode] = prov.n;
      let provCity = prov.s;
      if (!provCity) { //一些国家下面没有具体地区
        // console.log("没有具体地区");
        // console.log(prov);
        continue;
      }
      for (let l = 0, m = provCity.length; l < m; ++l) {
        let cityCode = provCode + (l + 1) * 100;
        let city = provCity[l];
        abroadCity[cityCode] = city.n;
        let cityCounty = city.s;
        if (!cityCounty) { //一些市下面，没有县
          continue;
        }

        for (let p = 0, q = cityCounty.length; p < q; ++p) {
          let countyCode = cityCode + p + 1;
          let county = cityCounty[p];
          abroadCounty[countyCode] = county.n;
        }
      }
    }

    this.setData({
      abroadList: {
        province_list: abroadProv,
        city_list: abroadCity,
        county_list: abroadCounty
      }
    });
  },

  //获取地址json，要用wx.request
  getAddrJson() {
    let that = this;
    let wxReq = util.wxPromisify(wx.request);
    wxReq({
      url: util.host + '/assets/libs/fastadmin-cxselect/js/globalData.min.json'
    }).then(res => {
      console.log("--------------getAddrJson");
      console.log(res.data);
      that.formatAddr(res.data);

      that.formatAbroadAddr(res.data);

    }).catch(err => {
      console.log(err);
      wx.showToast({
        title: String(err),
        icon: 'none',
        duration: 2000
      })
    })
  },
  onLoad: function(options) {
    let that = this;
    this.setData({
      nowType: options.index
    })
    var value = wx.getStorageSync('searchData')
    if (value) {
      util.http({
        url: '/api/miniwechat/index/search',
        method: 'POST',
        data: value
      }).then(res => {
        console.log("-------------👇");
        console.log(res);
        if (!res.line.rows) {
          wx.showToast({
            title: '查无数据',
            icon: 'none',
            duration: 2000
          })
          return;
        }
        res.line.rows.forEach((item, index) => {
          if (!item.line_time_list || item.line_time_list.length == 0) {
            return;
          }
          let beginTime = item.line_time_list.begin_time
          let endTime = item.line_time_list.end_time
          console.log(beginTime)
          console.log(endTime)
          let totalTime = (new Date(endTime).getTime() - new Date(beginTime).getTime()) / (1 * 24 * 60 * 60 * 1000)
          let surplusNum = item.line_time_list.quota - item.line_time_list.number
          item.line_time_list.totalTime = totalTime
          item.line_time_list.begin_time = timeReset(beginTime)
          item.line_time_list.end_time = timeReset(endTime)
          item.line_time_list.surplusNum = surplusNum
          switch (item.line_time_list.status) {
            case 0:
              item.line_time_list.state = '已取消'
              break;
            case 1:
              item.line_time_list.state = '报名中'
              break;
            case 2:
              item.line_time_list.state = '报名结束'
              break;
            case 3:
              item.line_time_list.state = '已完成'
              break;
          }
        })
        //渲染搜索结果↓↓↓↓↓↓↓↓↓↓↓↓↓
        that.setData({
          routeList: this.initPartner(res.line.rows, 2),
          expertList: res.guide.rows,
          screenShow: false,
          keyShow: true
        })
      }).catch(err => {
        console.log(err);
        wx.showToast({
          title: String(err),
          icon: 'none',
          duration: 2000
        })
      })
    } else {
      this.getSearch();
    }



  },
  // attached() {
  //   console.log(this.data.routeList);
  //   this.getLineClassify();
  //   this.getAddrJson();
  //   this.getSearch();
  // }
})

function timeReset(time) {
  let arr = time.split("-")
  arr.splice(0, 1)
  arr = arr.join(".")
  return arr
}